import 'dart:ffi';

import 'package:dance_todo/db/bean_event.dart';
import 'package:dance_todo/db/bean_record.dart';
import 'package:dance_todo/main.dart';
import 'package:dance_todo/objectbox.g.dart';
import 'package:dance_todo/res/res_keys.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:objectbox/objectbox.dart';

class HomeCtrl extends GetxController {
  static HomeCtrl get to => Get.find();

  // final curStep = 0.obs;
  final selectRecord = Record().obs;

  @override
  void onInit() {
    super.onInit();
    //获取当前选择的Event
    getSelectRecord();
  }

  ///获取选择的事件
  void getSelectRecord() {
    final box = GetStorage();
    int? selectRecordId = box.read<int>(KEY_SELECT_RECORD_ID);
    if (selectRecordId == null) {
      selectRecord.value = Record();
      selectRecord.refresh();
      return;
    }

    final query = recordBox.query(Record_.id.equals(selectRecordId)).build();
    List<Record> findRecords = query.find();
    if (findRecords.isEmpty) {
      selectRecord.value = Record();
      selectRecord.refresh();
      return;
    }
    query.close();
    //判断是否为当天的记录
    Record findRecord = findRecords[0];
    int year = findRecord.date!.year;
    int month = findRecord.date!.month;
    int day = findRecord.date!.day;
    if (year != DateTime.now().year ||
        month != DateTime.now().month ||
        day != DateTime.now().day) {
      findRecord = Record();
    }

    selectRecord.value = findRecord;
    selectRecord.refresh();
    return;
  }

  void saveRecord(Record record) {
    selectRecord.value = record;
    selectRecord.refresh();
    recordBox.put(record);
  }
}
